//
//  TMCommodityDetailController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/7/5.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMCommodityDetailController.h"
#import "TMCommityDetailHeader.h"
#import "TMCommityContentCell.h"
#import "TMTeacherDiscriptCell.h"
#import "TMTotalCommentCell.h"
#import "TMTeacherCommentCell.h"
#import "TMCommityBarView.h"
#import "TMBuyGoodsController.h"
#import "TMShoppingCartController.h"
#import "TMHomeViewModel.h"
#import "TMCourseDetailModel.h"
#import "TMUserViewModel.h"
#import "TMConversationController.h"
#import "TMOrderModel.h"
#import "TMMyCourseModel.h"
#import "TMUseDiscountView.h"
#import "TMNearbyViewModel.h"
#import "NSDate+STFormatter.h"
@interface TMCommodityDetailController ()<UITableViewDelegate, UITableViewDataSource,RCIMUserInfoDataSource>
@property (weak, nonatomic) IBOutlet UITableView *detailTab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConst;
@property (weak, nonatomic) IBOutlet UIView *barView;
@property (nonatomic, weak) TMCommityDetailHeader *detailHeader;
@property (nonatomic, strong) TMHomeViewModel *viewModel;
@property (nonatomic, strong) TMCourseDetailModel *models;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) TMUserViewModel *userViewModel;
@property (nonatomic, strong) TMUseDiscountView *discountDetailView;
@property (nonatomic, strong) TMNearbyViewModel *nearViewModel;
@property (nonatomic, strong) TMCommityBarView *buttomView;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger totalNum;
@property(nonatomic, assign) bool                     isDown;/**< 是否下架，超过下架时间下架， 或者under = 0*/
@end

@implementation TMCommodityDetailController
- (NSMutableArray *)listArray{
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}
- (bool)isDown{
    if (self.models.under.integerValue == 0 ) {
        return YES;
    }
    NSInteger current = [NSDate.date timeIntervalSince1970];
    if (current >= self.models.down_time.integerValue) {
        return YES;
    }
    return NO;
}
-(TMUseDiscountView*)discountDetailView{
    if (_discountDetailView == nil) {
        _discountDetailView = [[NSBundle mainBundle] loadNibNamed:@"TMDiscountDetailView" owner:nil options:nil][2];
    }
    return _discountDetailView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self regsiterCells];
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    self.title = self.isDiscount ? @"优惠券":@"商品详情";
    self.userViewModel = [[TMUserViewModel alloc]init];
    self.nearViewModel = [[TMNearbyViewModel alloc]init];
    self.detailTab.tableFooterView = [UIView new];
    self.detailTab.backgroundColor = [UIColor whiteColor];
    self.detailTab.delegate = self;
    self.detailTab.dataSource = self;
    self.detailTab.rowHeight = UITableViewAutomaticDimension;
    self.detailTab.contentInset = UIEdgeInsetsMake(-35, 0, 0, 0);
    // 设置内容指示器(滚动条)的内边距
    self.detailTab.scrollIndicatorInsets = self.detailTab.contentInset;
    [self displayBarView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(useDiscont:) name:@"GETDISCOUNTNOTI" object:nil];
    self.viewModel = [[TMHomeViewModel alloc]init];
    __weak typeof(self) weakSelf =  self;
    self.detailTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageNum =1;
        [weakSelf.viewModel getRecommendDetailParam:weakSelf.rid Page:weakSelf.pageNum Success:^(id responseObject, id responseObject1) {
            weakSelf.models = responseObject;
            weakSelf.totalNum = weakSelf.models.totalPage;
            weakSelf.buttomView.shoppingCarNumLabel.text = [NSString stringWithFormat:@"%ld", weakSelf.models.car_num];
            weakSelf.listArray = responseObject1;
            [weakSelf.detailTab reloadData];
            [weakSelf.detailTab.mj_header endRefreshing];
            [weakSelf.detailTab.mj_footer endRefreshing];
        } Failed:^(NSString *error) {
            [weakSelf.detailTab.mj_header endRefreshing];
            [weakSelf.detailTab.mj_footer endRefreshing];
        }];
    }];
    [self.detailTab.mj_footer beginRefreshing];
    self.detailTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageNum ++;
        if (weakSelf.pageNum > weakSelf.totalNum) {
            [weakSelf.detailTab.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        [weakSelf.viewModel getRecommendDetailParam:weakSelf.rid Page:weakSelf.pageNum Success:^(id responseObject, id responseObject1) {
            weakSelf.models = responseObject;
            weakSelf.totalNum = weakSelf.models.totalPage;
            weakSelf.buttomView.shoppingCarNumLabel.text = [NSString stringWithFormat:@"%ld", weakSelf.models.car_num];
            weakSelf.listArray = responseObject1;
            [weakSelf.detailTab reloadData];
            [weakSelf.detailTab.mj_header endRefreshing];
            [weakSelf.detailTab.mj_footer endRefreshing];
        } Failed:^(NSString *error) {
            if (weakSelf.pageNum > 1) {
                weakSelf.pageNum--;
            }
            [weakSelf.detailTab.mj_header endRefreshing];
            [weakSelf.detailTab.mj_footer endRefreshing];
        }];
    }];
    [self.detailTab.mj_header beginRefreshing];
}
- (void)displayBarView{
    _buttomView = [[NSBundle mainBundle] loadNibNamed:@"TMCommityBarView" owner:self options:nil][0];
    [self.barView addSubview:_buttomView];
    if (!self.models.car_num) {
        self.models.car_num = 0 ;
    }
    _buttomView.shoppingCarNumLabel.text = [NSString stringWithFormat:@"%ld", self.models.car_num];
    [_buttomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.barView);
        make.left.equalTo(self.barView);
        make.size.mas_equalTo(self.barView);
    }];
    __weak typeof(self) weakself = self;
    __weak typeof(_buttomView) weakview = _buttomView;

    _buttomView.carBlock = ^{
        if ([TMUserManager deaufatManager].userModel.token == nil) {
            MUST_LOGIN_ALERT;
            return;
        }
        //
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"YYYY-MM-dd"];
//        NSDate *datenow = [NSDate date];
//        NSString *currentTimeString = [formatter stringFromDate:datenow];
//        //s_time
//        NSInteger result =  [SPToolSet compareDate:[SPToolSet stringFromDateString:weakself.models.s_time] withDate:currentTimeString];
//        if (result == 1) {
//            [TMProgressHUD showInfoWithStyleDarkStatus:@"当前课程已开课无法购买！"];
//            return;
//        }
        //加入购物车
        if (weakself.isDown) {
            [TMProgressHUD showInfoWithStyleDarkStatus:@"当前课程已下架，无法加入购物车!"];
            return;
        }
        [weakself.viewModel addShoppingCartParam:weakself.models.cid Success:^(id responseObject) {
        weakview.shoppingCarNumLabel.text = [NSString stringWithFormat:@"%ld", ++weakself.models.car_num ];
        } Failed:^(NSString *error) {
            
        }];
    };
    
    _buttomView.block = ^(TapViewType type) {
        if ([TMUserManager deaufatManager].userModel.token == nil) {
            MUST_LOGIN_ALERT;
            return;
        }
        if (type == TapViewTypeCustomerService) {
            RCConversationViewController *conversationVC = [[RCConversationViewController alloc]init];
            //聊天界面的聊天类型
            conversationVC.conversationType = ConversationType_PRIVATE;
            conversationVC.title = @"客服";
            conversationVC.targetId = [NSString stringWithFormat:@"%ld", (long)weakself.models.uid];//83
            RCUserInfo *info = [[RCUserInfo alloc]initWithUserId:[NSString stringWithFormat:@"%ld",[TMUserManager deaufatManager].userModel.uid] name:[TMUserManager deaufatManager].userModel.userName portrait:[NSString stringWithBaseUrl:[TMUserManager deaufatManager].userModel.userimage]];
            [RCIM sharedRCIM].currentUserInfo = info;
            [weakself.navigationController pushViewController:conversationVC animated:YES];
        }
        if (type == TapViewTypeShoppingCar) {
            TMShoppingCartController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMShoppingCartController"];
            [weakself.navigationController pushViewController:vc animated:YES];
        }
//        if (type == TapViewTypeAddShopView) {
//
//        }
        if (type == TapViewTypePurcuse) {
            //购买
            //判断 时间。 座位。
            if (weakself.models.surplus == 0) {
                [TMProgressHUD showInfoWithStyleDarkStatus:@"当前课程剩余座位不足！"];
                return;
            }
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            [formatter setDateFormat:@"YYYY-MM-dd"];
//            NSDate *datenow = [NSDate date];
//            NSString *currentTimeString = [formatter stringFromDate:datenow];
            //s_time
//            NSInteger result =  [SPToolSet compareDate:[SPToolSet stringFromDateString:weakself.models.s_time] withDate:currentTimeString];
//            if (result == 1) {
//                [TMProgressHUD showInfoWithStyleDarkStatus:@"当前课程已开课无法购买！"];
//                return;
//            }
            //立刻购买
            
            if (weakself.isDown) {
                [TMProgressHUD showInfoWithStyleDarkStatus:@"当前课程已下架，无法购买!"];
                return;
            }
            
            
            TMBuyGoodsController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMBuyGoodsController"];
            vc.listDic = @[[NSString stringWithFormat:@"%ld", weakself.models.cid]].mutableCopy;
            vc.isFromBuy = YES;
            //vc.cid = self.models.cid;
            [weakself.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion{
    
    NSLog(@"%@", userId);
    [self.viewModel getChatInformationWith:[userId integerValue] Success:^(id responseObject) {
        RCUserInfo *infor = [[RCUserInfo alloc]initWithUserId:userId name:responseObject[@"list"][@"username"] portrait:[NSString stringWithBaseUrl:responseObject[@"list"][@"userimage"]]];
        completion(infor);
    } failed:^(NSString *error) {
        
    }];
    
}

- (void)useDiscont:(NSNotification *)noti{
    //@{@"usid":@(self.model.usid),@"price":@(self.model.money)}
    NSInteger did = [noti.userInfo[@"usid"] integerValue];
    if (self.navigationController.childViewControllers.lastObject == self) {
        [self.nearViewModel getToUsrDiscountWith:did Success:^(id responseObject) {
            
        } failed:^(NSString *error) {
            
        }];
    }

}
- (void)regsiterCells{
    [self.detailTab registerNib:[UINib nibWithNibName:@"TMCommityContentCell" bundle:nil] forCellReuseIdentifier:@"TMCommityContentCell"];
    [self.detailTab registerNib:[UINib nibWithNibName:@"TMTeacherDiscriptCell" bundle:nil] forCellReuseIdentifier:@"TMTeacherDiscriptCell"];
    [self.detailTab registerNib:[UINib nibWithNibName:@"TMTotalCommentCell" bundle:nil] forCellReuseIdentifier:@"TMTotalCommentCell"];
    [self.detailTab registerNib:[UINib nibWithNibName:@"TMTeacherCommentCell" bundle:nil] forCellReuseIdentifier:@"TMTeacherCommentCell"];
}

#pragma mark table header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (!_detailHeader) {
        _detailHeader = [[NSBundle mainBundle] loadNibNamed:@"TMTeacherDetailHeader" owner:self options:nil][1];
    }
    _detailHeader.isdisconut = self.isDiscount;
    _detailHeader.headModel = self.models;
    __weak typeof(self) weakself = self;
    _detailHeader.block = ^(NSInteger cid) {
        if ([TMUserManager deaufatManager].userModel.token == nil) {
            MUST_LOGIN_ALERT;
            return;
        }
        [weakself.userViewModel getCommitCollectionWith:cid Success:^(id responseObject) {
            
        } failed:^(NSString *error) {
            
        }];
    };
    _detailHeader.discountBlock = ^(NSInteger code) {
        if ([TMUserManager deaufatManager].userModel.token == nil) {
            MUST_LOGIN_ALERT;
            return;
        }
        if (code == 2) {
            [weakself.nearViewModel getToOrderCourseWith:weakself.models.cid Success:^(id responseObject) {
                [weakself.detailHeader.canOrderBtn setTitle:@"已预约" forState:UIControlStateNormal];
            } failed:^(NSString *error) {
                [weakself.detailHeader.canOrderBtn setTitle:@"可预约" forState:UIControlStateNormal];
            }];
        }else{
        if (weakself.discountDetailView) {
            [weakself.discountDetailView removeFromSuperview];
        }
        [weakself discountDetailView];
        weakself.discountDetailView.cid = weakself.models.uid;
        weakself.discountDetailView.realCid = weakself.models.cid;
        weakself.discountDetailView.type = WhereDiscountUse;
        weakself.discountDetailView.frame = CGRectMake(0, 0, weakself.navigationController.view.bounds.size.width, weakself.navigationController.view.bounds.size.height);
        [weakself.navigationController.view addSubview:weakself.discountDetailView];
            NSLog(@"22222");
        }
    };
    return _detailHeader;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.isDiscount == YES) {
        return 307 -90;
    }else{
    return 307;
    }
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isDiscount == YES) {
        return 1;
    }else{
    return 3 + self.listArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf =  self;
    if (self.isDiscount == YES) {
        TMCommityContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMCommityContentCell"];
        cell.isdiscount = YES;
        return cell;
    }else{
    if (indexPath.row == 0) {
        TMCommityContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMCommityContentCell"];
        cell.isdiscount = NO;
        cell.contentLabel.text = [NSString stringWithFormat:@"商品简介:%@", self.models.suggest];
        return cell;
    }else if (indexPath.row == 1){
        TMTeacherDiscriptCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMTeacherDiscriptCell"];
        cell.model = self.models;
        cell.showBlock = ^(BOOL isok){
            weakSelf.models.show = isok;
            [weakSelf.detailTab reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        };
        return cell;
    }else if (indexPath.row == 2){
        TMTotalCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMTotalCommentCell"];
        cell.totalNum.text = [NSString stringWithFormat:@"总体评价(%ld)", self.models.total];
        for (NSInteger i = 0; i < self.models.average; i ++) {
            UIButton *btn = cell.starcollection[i];
            btn.selected = YES;
        }
        return cell;
    }else{
        TMTeacherCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMTeacherCommentCell"];
        cell.model = self.listArray[indexPath.row -3];
        return cell;
    }
    }
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//}
//- (void)displayDate:(NSString *)str{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"YYYY-MM-dd"];
//    NSDate *datenow = [NSDate date];
//    NSString *currentTimeString = [formatter stringFromDate:datenow];
//    //s_time
//    NSInteger result =  [SPToolSet compareDate:[SPToolSet stringFromDateString:self.models.s_time] withDate:currentTimeString];
//    if (result == 1) {
//        [TMProgressHUD showInfoWithStyleDarkStatus:str];
//        return;
//    }
//}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.discountDetailView) {
        [self.discountDetailView removeFromSuperview];
        self.discountDetailView = nil;
    }
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.detailTab.mj_header beginRefreshing];
}
@end
